import 'package:flutter/material.dart';
import 'dart:async';

void main() {
  runApp(const DartFunctionsApp());
}

class DartFunctionsApp extends StatelessWidget {
  const DartFunctionsApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Dart 函数特性演示',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: const FunctionDemoScreen(),
    );
  }
}

class FunctionDemoScreen extends StatefulWidget {
  const FunctionDemoScreen({super.key});

  @override
  State<FunctionDemoScreen> createState() => _FunctionDemoScreenState();
}

class _FunctionDemoScreenState extends State<FunctionDemoScreen> {
  String _output = '';
  bool _isLoading = false;
  final ScrollController _scrollController = ScrollController();

  // 1. 顶级函数定义
  bool isNoble(int atomicNumber) {
    return _nobleGases[atomicNumber] != null;
  }

  final Map<int, String> _nobleGases = {2: 'He', 10: 'Ne', 18: 'Ar'};

  // 2. 箭头函数
  bool isNobleShorthand(int atomicNumber) => _nobleGases[atomicNumber] != null;

  // 3. 命名参数函数
  void enableFlags({bool? bold, bool hidden = false, required String message}) {
    _log('bold: $bold, hidden: $hidden, message: $message');
  }

  // 4. 可选位置参数函数
  String say(String from, String msg, [String? device]) {
    var result = '$from says "$msg"';
    if (device != null) result += ' with a $device';
    return result;
  }

  // 辅助函数：打印元素
  void printElement(int element) {
    _log('Element: $element');
  }

  // 闭包示例
  Function makeAdder(int addBy) {
    return (int i) => addBy + i;
  }

  // 同步生成器
  Iterable<int> naturalsTo(int n) sync* {
    int k = 0;
    while (k < n) yield k++;
  }

  // 异步生成器
  Stream<int> asynchronousNaturalsTo(int n) async* {
    int k = 0;
    while (k < n) {
      yield k++;
      await Future.delayed(const Duration(seconds: 1));
    }
  }

  // 测试函数相等性
  void testFunctionEquality() {
    // 比较顶级函数
    Function func1 = isNoble;
    _log('顶级函数相等性: ${isNoble == func1}');

    // 比较静态方法
    Function func2 = A.staticMethod;
    _log('静态方法相等性: ${A.staticMethod == func2}');

    // 比较实例方法
    var a1 = A();
    var a2 = A();
    _log('实例方法相等性: ${a1.instanceMethod == a2.instanceMethod}');
  }

  // 运行单个演示
  void _runDemo(String demoType) async {
    _clearOutput();
    setState(() => _isLoading = true);

    switch (demoType) {
      case 'topLevel':
        _log('\n=== 顶级函数演示 ===');
        _log('元素 10 是否为惰性气体: ${isNoble(10)}');
        _log('元素 7 是否为惰性气体: ${isNobleShorthand(7)}');
        break;

      case 'namedParameters':
        _log('\n=== 命名参数函数演示 ===');
        enableFlags(message: 'Hello');
        enableFlags(bold: true, message: 'Bold Text');
        enableFlags(hidden: true, message: 'Hidden Message');
        break;

      case 'positionalParameters':
        _log('\n=== 可选位置参数函数演示 ===');
        _log(say('Alice', 'Hi'));
        _log(say('Bob', 'Hello', 'phone'));
        break;

      case 'firstClass':
        _log('\n=== 函数作为一等公民演示 ===');
        var greet = (String name) => '你好, $name!';
        _log(greet('Flutter'));

        List<int> numbers = [1, 2, 3];
        numbers.forEach(printElement);

        var add = makeAdder(5);
        _log('5 + 3 = ${add(3)}');
        break;

      case 'generators':
        _log('\n=== 生成器函数演示 ===');
        _log('同步生成器:');
        for (int n in naturalsTo(5)) {
          _log('$n');
          await Future.delayed(const Duration(milliseconds: 300));
        }

        _log('\n异步生成器:');
        await for (int n in asynchronousNaturalsTo(3)) {
          _log('$n (延迟1秒)');
        }
        break;

      case 'equality':
        _log('\n=== 函数相等性测试 ===');
        testFunctionEquality();
        break;
    }

    setState(() => _isLoading = false);
  }

  // 运行所有演示
  void _runAllDemos() async {
    _clearOutput();
    setState(() => _isLoading = true);

    _log('正在运行所有函数特性演示...\n');
    await Future.delayed(const Duration(seconds: 1));

    _runDemo('topLevel');
    await Future.delayed(const Duration(seconds: 1));

    _runDemo('namedParameters');
    await Future.delayed(const Duration(seconds: 1));

    _runDemo('positionalParameters');
    await Future.delayed(const Duration(seconds: 1));

    _runDemo('firstClass');
    await Future.delayed(const Duration(seconds: 1));

    _runDemo('generators');
    await Future.delayed(const Duration(seconds: 1));

    _runDemo('equality');

    _log('\n所有演示运行完毕!');
    setState(() => _isLoading = false);
  }

  // 辅助方法
  void _log(String message) {
    setState(() {
      _output += '$message\n';
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    });
  }

  void _clearOutput() {
    setState(() {
      _output = '';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Dart 函数特性演示'), centerTitle: true),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 功能按钮区域
            Wrap(
              spacing: 8.0,
              runSpacing: 8.0,
              children: [
                ElevatedButton(
                  onPressed: () => _runDemo('topLevel'),
                  child: const Text('顶级函数'),
                ),
                ElevatedButton(
                  onPressed: () => _runDemo('namedParameters'),
                  child: const Text('命名参数'),
                ),
                ElevatedButton(
                  onPressed: () => _runDemo('positionalParameters'),
                  child: const Text('位置参数'),
                ),
                ElevatedButton(
                  onPressed: () => _runDemo('firstClass'),
                  child: const Text('一等公民'),
                ),
                ElevatedButton(
                  onPressed: () => _runDemo('generators'),
                  child: const Text('生成器'),
                ),
                ElevatedButton(
                  onPressed: () => _runDemo('equality'),
                  child: const Text('函数相等性'),
                ),
                ElevatedButton(
                  onPressed: _runAllDemos,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.green,
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (_isLoading)
                        const SizedBox(
                          width: 16,
                          height: 16,
                          child: CircularProgressIndicator(
                            color: Colors.white,
                            strokeWidth: 2,
                          ),
                        ),
                      if (_isLoading) const SizedBox(width: 8),
                      const Text('运行全部'),
                    ],
                  ),
                ),
              ],
            ),

            const SizedBox(height: 16),

            // 输出区域
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey.shade300),
                  borderRadius: BorderRadius.circular(8),
                  color: Colors.grey.shade50,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Container(
                      padding: const EdgeInsets.all(8),
                      color: Colors.grey.shade200,
                      child: const Text(
                        '输出结果',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                    ),
                    Expanded(
                      child: SingleChildScrollView(
                        controller: _scrollController,
                        padding: const EdgeInsets.all(12),
                        child: SelectableText(
                          _output.isEmpty ? '点击上方按钮运行演示...' : _output,
                          style: const TextStyle(
                            fontFamily: 'monospace',
                            fontSize: 14,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 测试函数相等性的辅助类
class A {
  static void staticMethod() => print('Static method');
  void instanceMethod() => print('Instance method');
}
